package com.hmall.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdmall.business.common.common.Const;
import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.*;
import com.hmall.controller.JpushController;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.*;
import com.hmall.vo.*;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zhoutao
 * @Date 2018/11/8 16:58
 * @Param
 * @return
 * @Description //
 */
@Slf4j
@Service
public class UserService {

    private final SysUserMapper userMapper;

    private final SysCustomerStatementMapper sysCustomerStatementMapper;

    private final MallPaymentVoucherMapper mallPaymentVoucherMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    private final MallOrderMapper orderMapper;

    private final MallOrderItemMapper orderItemMapper;

    private final SysUserDetailMapper sysUserDetailMapper;

    private final SysUserTempMapper sysUserTempMapper;

    private final SysDeptMapper sysDeptMapper;

    private final SysUserDeptMapper sysUserDeptMapper;

    private final SysUserExtraMapper sysUserExtraMapper;

    private final MallDealerMapper mallDealerMapper;

    private final MallProductMapper mallProductMapper;

    private final MallShopMapper mallShopMapper;

    private final MallHotMapper mallHotMapper;

    private final MallPriceMapper mallPriceMapper;

    private final SysUserFavoriteMapper sysUserFavoriteMapper;

    private final SysCustomerMapper sysCustomerMapper;

    private final SysDeptCustomerMapper sysDeptCustomerMapper;

    private final MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper;

    private final SysCustomerCreditTransactionMapper sysCustomerCreditTransactionMapper;

    private final SysCustomerCreditMapper sysCustomerCreditMapper;

    private final SysMenuMapper menuMapper;

    private final MallPaymentUnpayMapper mallPaymentUnpayMapper;

    private final JpushController jpushController;

    private final JedisPool jedisPool;

    private EnvUtil envUtil = new EnvUtil();

    private final BiUserAnalysisMapper biUserAnalysisMapper;

    private final MobileHomeService mobileHomeService;

    private final JpushService jpushService;

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private final SysUserCertificationMapper sysUserCertificationMapper;


    @Autowired
    public UserService(MallPaymentVoucherMapper mallPaymentVoucherMapper, SysUserMapper userMapper, SysCustomerStatementMapper sysCustomerStatementMapper, SysUserRoleMapper sysUserRoleMapper, MallOrderMapper orderMapper, MallOrderItemMapper orderItemMapper, MallOrderFufillmentParentMapper mallOrderFufillmentParentMapper, SysUserDetailMapper sysUserDetailMapper, MallDealerMapper mallDealerMapper, MallPaymentUnpayMapper mallPaymentUnpayMapper, SysCustomerMapper sysCustomerMapper, SysUserTempMapper sysUserTempMapper, SysDeptMapper sysDeptMapper, SysDeptCustomerMapper sysDeptCustomerMapper, SysCustomerCreditMapper sysCustomerCreditMapper, MallPriceMapper mallPriceMapper, JpushController jpushController, SysCustomerCreditTransactionMapper sysCustomerCreditTransactionMapper, SysUserFavoriteMapper sysUserFavoriteMapper, SysUserDeptMapper sysUserDeptMapper, JedisPool jedisPool, MallProductMapper mallProductMapper, SysUserExtraMapper sysUserExtraMapper, MallShopMapper mallShopMapper, MallHotMapper mallHotMapper, SysMenuMapper menuMapper, BiUserAnalysisMapper biUserAnalysisMapper, MobileHomeService mobileHomeService, JpushService jpushService, SysUserCertificationMapper sysUserCertificationMapper) {
        this.mallPaymentVoucherMapper = mallPaymentVoucherMapper;
        this.userMapper = userMapper;
        this.sysCustomerStatementMapper = sysCustomerStatementMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.orderMapper = orderMapper;
        this.orderItemMapper = orderItemMapper;
        this.mallOrderFufillmentParentMapper = mallOrderFufillmentParentMapper;
        this.sysUserDetailMapper = sysUserDetailMapper;
        this.mallDealerMapper = mallDealerMapper;
        this.mallPaymentUnpayMapper = mallPaymentUnpayMapper;
        this.sysCustomerMapper = sysCustomerMapper;
        this.sysUserTempMapper = sysUserTempMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.sysCustomerCreditMapper = sysCustomerCreditMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.jpushController = jpushController;
        this.sysCustomerCreditTransactionMapper = sysCustomerCreditTransactionMapper;
        this.sysUserFavoriteMapper = sysUserFavoriteMapper;
        this.sysUserDeptMapper = sysUserDeptMapper;
        this.jedisPool = jedisPool;
        this.mallProductMapper = mallProductMapper;
        this.sysUserExtraMapper = sysUserExtraMapper;
        this.mallShopMapper = mallShopMapper;
        this.mallHotMapper = mallHotMapper;
        this.menuMapper = menuMapper;
        this.biUserAnalysisMapper = biUserAnalysisMapper;
        this.mobileHomeService = mobileHomeService;
        this.jpushService = jpushService;
        this.sysUserCertificationMapper = sysUserCertificationMapper;
    }

    public ServerResponse<String> delete(String account) {
        List<SysUser> userList = userMapper.selectAccout(account);
        if (null == userList || userList.size() == 0) {
            return ServerResponse.createByErrorCodeMessage(-1, "查询用户失败");

        }
        for (SysUser user : userList) {
            try {
                userMapper.deleteUser(user.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorCodeMessage(-1, "用户删除失败");
            }
            sysUserDeptMapper.deleteByUserId(user.getUserId());
            sysUserDetailMapper.deleteByUserId(user.getUserId());
            sysUserRoleMapper.deleteByUserId(user.getUserId());
            sysUserTempMapper.deleteByUserId(user.getUserId());
            orderMapper.deleteByUserId(user.getUserId());
            orderItemMapper.deleteByUserId(user.getUserId());
        }

        return ServerResponse.createBySuccess("删除用户成功");
    }

    public static String getIP(HttpServletRequest request){
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
        String ip = (String)request.getAttribute("remote-user-ip");
        if(ip == null){
            ip = request.getHeader("remote-user-ip");
        }
        return ip;
    }
    /**
     * @Date 2018/11/8 16:54
     * @Param [request, agentUserName, password]
     * @return com.hmall.common.ServerResponse<java.util.Map<java.lang.String,java.lang.String>>
     * @Description // 登录
     */
    public ServerResponse<LoginUserVo> login(HttpServletRequest request, String agentUserName, String password, String deviceToken) {

        //deviceToken 唯一信息

//        String ip = getIP(request);
        String ip = (String)request.getAttribute("remote-user-ip");
        if(ip == null){
            ip = request.getHeader("remote-user-ip");
        }
        String userAgent = request.getHeader("user-agent");


        Map<String, String> map = new HashMap<>(16);
        map.put("ip", ip);
        map.put("user_agent", userAgent);

        String url = envUtil.getPreUrl("order");
        url += "/bi/actionHistoryBiInsert";
        String response = HttpClientUtil.doGetWithParam(url, map);
        log.info(response);

        //带了设备头  ANDROID- , IOS- , PC-
        String []str = AgentUtil.deleteAgentUserName(agentUserName).getData().split(":");
        String agent = str[0];
        String username = str[1];


        if (agent == null) {
            return ServerResponse.createByStatus(19, "未知设备,无法登陆");
        }


        int count = userMapper.checkUsername(username);
        if (count <= 0) {
            return ServerResponse.createByStatus(11, "用户名不存在");
        }


        String encryptPassword;
        //在普通用户列表里查询
        SysUser normalUser = userMapper.selectNomalUserByUserName(username);
        encryptPassword = MD5Util.MD5EncodeUtf8(password);
        if (normalUser != null && normalUser.getPassword().equals(encryptPassword)) {

            //2018/12/21 需要记录设备信息
            recordBiUserAnalysis(ip, username, agent, request);
            log.info("记录信息成功");
            try {
                return loginSubMethod(normalUser, agent, deviceToken);
            } catch (IOException e) {
                return ServerResponse.createByErrorMessage("登陆失败");
            }

        } else {
            return ServerResponse.createByErrorMessage("密码错误");
        }

    }

    private void recordBiUserAnalysis(String ip, String username, String agent, HttpServletRequest request){

        String dataType = "UV";
        //同一天同一个username只能够3次
        //同一个ip一天最多十次
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH);
        Integer date = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(year, month, date, 0, 0, 0);
        Date startTime = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date endTime = calendar.getTime();
        Integer usernameCount = biUserAnalysisMapper.selectCountByUsername(username, startTime, endTime, dataType);
        if(usernameCount >= 1) {
            log.info("用户名为" + username + "的用户本日已经登录了一次无法进行统计");
            return;
        }
        Integer ipCount = biUserAnalysisMapper.selectCountByIp(ip, startTime, endTime, dataType);
        if(ipCount >= 10){
            log.info("IP为" + ip + "的用户本日已经连续登录了十次无法进行统计");
            return;
        }

        BiUserAnalysis biUserAnalysis = new BiUserAnalysis();
        biUserAnalysis.setIp(ip);
        //2代表UV
        biUserAnalysis.setDataType("UV");
        biUserAnalysis.setCreateTime(new Date());
        Integer userId = userMapper.selectByUserName1(username).getUserId();
        biUserAnalysis.setUserId(userId);
        agent = agent.split("-")[0];
        biUserAnalysis.setDeviceType(agent);
        String deviceBrand = request.getParameter("deviceBrand");
        String []deviceBrandList = {"huawei","oppo", "vivo", "samsung", "meizu"};
        String cnDeviceBrand = "";
        if(deviceBrand == null) {
            cnDeviceBrand = "其他型号";
        }else {
            if ("ANDROID".equals(agent)) {
                for (String defaultDeviceBrand : deviceBrandList) {
                    deviceBrand = deviceBrand.toLowerCase();
                    if (defaultDeviceBrand.equals(deviceBrand)) {
                        switch (deviceBrand) {
                            case "huawei": {
                                cnDeviceBrand = "华为";
                                break;
                            }
                            case "oppo": {
                                cnDeviceBrand = "OPPO";
                                break;
                            }
                            case "vivo": {
                                cnDeviceBrand = "VIVO";
                                break;
                            }
                            case "samsung": {
                                cnDeviceBrand = "三星";
                                break;
                            }
                            case "meizu": {
                                cnDeviceBrand = "meizu";
                                break;
                            }
                            default: {
                                cnDeviceBrand = "其他型号";
                                break;
                            }
                        }
                    } else {
                        cnDeviceBrand = "其他型号";
                    }
                }
            } else if ("IOS".equals(agent)) {
                cnDeviceBrand = "苹果";
            }
            if ("".equals(cnDeviceBrand)) {
                cnDeviceBrand = "其他型号";
            }
        }
        biUserAnalysis.setDeviceBrand(cnDeviceBrand);
        biUserAnalysisMapper.insert(biUserAnalysis);

    }

    public ServerResponse register(SysUser user) {

        //获得redis中的短信验证码
        Jedis jedis = jedisPool.getResource();
        String redisKey = "DEFAULT_CODE_KEY" + user.getUsername();
        if (jedis.get(redisKey) == null) {
            return ServerResponse.createByErrorMessage("短信验证错误");
        }
        String core = jedis.get(redisKey);
        jedis.close();

        int length = core.length();
        String realCore = core.substring(length - 4, length);
        //answer中传过来的是前端传过来的验证码
        if (!user.getAnswer().equals(realCore)) {
            return ServerResponse.createByErrorMessage("验证码错误");
        }

        ServerResponse response = subRegister(user);
        if (response.getStatus() != 0) {
            return response;
        }

        //删除登陆用的验证信息
        Jedis jedis1 = jedisPool.getResource();
        jedis1.del(redisKey);
        jedis1.close();
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    public ServerResponse subRegister(SysUser user) {

        //校验用户名
        ServerResponse validResponse = this.checkValid(user.getUsername());
        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        // user.setRole(Const.Role.ROLE_CUSTOMER);
        // MD5加密
        if (user.getPassword() != null) {
            user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        } else {
            user.setPassword(MD5Util.MD5EncodeUtf8(user.getUsername()));
        }
        //默认昵称
        if (user.getQuestion() == null) {
            user.setQuestion(user.getUsername());
        }

        String []avatorList = {Const.FRONT_AVATOR1, Const.FRONT_AVATOR2, Const.FRONT_AVATOR3, Const.FRONT_AVATOR4, Const.FRONT_AVATOR5, Const.FRONT_AVATOR6,
        Const.FRONT_AVATOR7, Const.FRONT_AVATOR8, Const.FRONT_AVATOR9};
        int index = new Random().nextInt(9);

        if (user.getAvatar() == null) {
            user.setAvatar(avatorList[index]);
        }
        user.setCreateTime(new Date());
        user.setDelFlag("0");
        //9是默认启用状态
        user.setStatus(9);
        //插入
        try {
            System.out.println("register" + user);
            userMapper.insert(user);

        } catch (Exception e) {
            return ServerResponse.createByStatus(18, "用户信息注册失败");
        }
        return ServerResponse.createBySuccess();
    }


//      运营商号段如下：
//      中国联通号码：130、131、132、145（无线上网卡）、155、156、185（iPhone5上市后开放）、186、176（4G号段）、
//                    175（2015年9月10日正式启用，暂只对北京、上海和广东投放办理）
//      中国移动号码：134、135、136、137、138、139、147（无线上网卡）、150、151、152、157、158、159、182、183、187、188、178
//      中国电信号码：133、153、180、181、189、177、173、149 虚拟运营商：170、1718、1719
//      手机号前3位的数字包括：
//      1 :1
//      2 :3,4,5,7,8
//      3 :0,1,2,3,4,5,6,7,8,9
//      总结： 目前java手机号码正则表达式有：
//      a :"^1[3|4|5|7|8][0-9]\\d{4,8}$"    一般验证情况下这个就可以了
//      b :"^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$"
//      Pattern和Matcher详解（字符串匹配和字节码）http://blog.csdn.net/u010700335/article/details/44616451

    /**
     * @Date 2018/11/9 15:23
     * @Param [userName]
     * @return com.hmall.common.ServerResponse<java.lang.String>
     * @Description // 校验号码
     */
    public ServerResponse<String> checkValid(String userName) {
        //开始校验
        String regex = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
        if (userName.length() != 11) {
            return ServerResponse.createByStatus(18, "请输入正确的手机号码");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(userName);
            boolean isMatch = m.matches();
            if (!isMatch) {
                return ServerResponse.createByStatus(18, "请输入正确的手机号码");
            }
        }

        int resultCount = userMapper.checkUsername(userName);

        //1.如果该手机号已经注册过了
        if (resultCount > 0) {

            return ServerResponse.createByErrorMessage("用户名已存在");
        }


        return ServerResponse.createBySuccessMessage("可以注册");
    }




    public ServerResponse<String> resetPassword(Jedis jedis, String userName, String code, String newPassword) {

        String resetCodeKey = "RESET_CODE_KEY";
        if (jedis.exists(resetCodeKey + userName)) {
            String redisCode = jedis.get(resetCodeKey + userName);

            System.out.println(redisCode);
            System.out.println(code);

            SysUser user = userMapper.selectByUserName1(userName);
            System.out.println(user);
            int length = redisCode.length();
            String realCore = redisCode.substring(length - 4, length);
            //如果验证码一致可以进行修改
            if (code.equals(realCore)) {
                user.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
                userMapper.updateByPrimaryKey(user);
                jedis.del(resetCodeKey + userName);
                return ServerResponse.createBySuccess("密码更新成功");
            }

            return ServerResponse.createByErrorMessage("密码更新失败");
        }

        return ServerResponse.createByErrorMessage("验证码不正确");

    }

    public ServerResponse<SysUser> updateInformation(SubUserInfoVo subUserInfoVo, Integer userId) {
        //username是不能被更新的
        //email也要进行一个校验,校验新的email是不是已经存在,并且存在的email如果相同的话,不能是我们当前的这个用户的.
      /*  int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getUserId());
        if(resultCount > 0){
            return ServerResponse.createByErrorMessage("email已存在,请更换email再尝试更新");
        }*/
        SysUser user = userMapper.selectByPrimaryKey(userId);
        if (!"".equals(subUserInfoVo.getNickName()) && subUserInfoVo.getNickName() != null) {
            user.setQuestion(subUserInfoVo.getNickName());
        }

        if (!"".equals(subUserInfoVo.getAvator()) && subUserInfoVo.getAvator() != null) {
            user.setAvatar(subUserInfoVo.getAvator());
        }
        List<SysUser> userList = userMapper.selectSubUser(user.getUsername().split("-")[0]);

        for(SysUser subUser : userList){
            if(!(subUser.getUsername().equals(user.getUsername().split("-")[0]) || subUser.getUsername().contains("-"))) {
                continue;
            }
            user.setUserId(subUser.getUserId());
            user.setUsername(subUser.getUsername());
            userMapper.updateByPrimaryKey(user);
        }
        return ServerResponse.createBySuccess();
    }

    /**
     * @Date 2018/11/9 15:25
     * @Param [userId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.UserInfoVo>
     * @Description // 获得用户基础信息
     */
    public ServerResponse<UserInfoVo> getInformation(HttpServletRequest request,Integer userId) {

        //2018/12/21 PV
        mobileHomeService.recordBiUserAnaysis(request);

        SysUser user = userMapper.selectByUserId(userId);
        if (user == null) {
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(user.getUserId());
        userInfoVo.setAvator(user.getAvatar());
        //question字段用来做昵称
        userInfoVo.setNickName(user.getQuestion());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setEmail(user.getEmail());
        userInfoVo.setDeptId(user.getDeptId());
        userInfoVo.setUserName(user.getUsername().split("-")[0]);
        SysCustomer sysCustomer = sysCustomerMapper.selectCustomerByUserId(userId);
        userInfoVo.setCustomerName(sysCustomer == null ? "" : sysCustomer.getBusName());
        //暂时在这里判断
        SysUserTemp userTemp = sysUserTempMapper.selectByUserId(userId);
        if (userTemp != null) {
            ServerResponse.createByStatus(16, "用户信息已提交，请勿重复提交");
        }
        // 0 :未提交审核 1:审核中 2: 审核失败 3: 审核通过 4: 资质取消
        if (userTemp == null) {
            userInfoVo.setStatus(0);
        } else {
            SysUserDept userDept = sysUserDeptMapper.selectbyUserId(userId);
            if(userDept != null){
                userInfoVo.setStatus(3);
            }else{
                //如果是成功的但是其实资质没有还要是没有
                if(userTemp.getStatus() == 3){
                    userInfoVo.setStatus(0);
                }else{
                    userInfoVo.setStatus(userTemp.getStatus());
                }



            }

        }
        SysUserDept sysUserDept = sysUserDeptMapper.selectbyUserId(userId);
        if (sysUserDept != null) {
            ServerResponse.createByStatus(16, "用户信息已提交，请勿重复提交");
        }
        //如果是办事处的
        if (user.getDeptId() != null && !user.getDeptId().equals(Const.MERCH_DEPT_ID) && user.getDeptId() != 11) {

            userInfoVo.setDealerName(mallDealerMapper.selectAllByDeptId(user.getDeptId()).getDealerName());
        }
        //实名认证参数
        Integer applyingCount = sysUserCertificationMapper.selectApplyingCount(userId);
        if (applyingCount >= 1) {
            userInfoVo.setCertificationStatus(0);
        }
        Integer applySuccessCount = sysUserCertificationMapper.selectApplySuccessCount(userId);
        if (applySuccessCount >= 1) {
            userInfoVo.setCertificationStatus(1);
        }
        Integer count = sysUserCertificationMapper.selectApplyCount(userId);
        if (count==0) {
            userInfoVo.setCertificationStatus(3);
            return ServerResponse.createBySuccess(userInfoVo);
        }
        SysUserCertification sysUserCertification = sysUserCertificationMapper.selectLastApply(userId);
        if (sysUserCertification.getIsPass()==2){
            userInfoVo.setCertificationStatus(2);
        }

        return ServerResponse.createBySuccess(userInfoVo);
    }



    /**
     * @Date 2018/11/9 15:26
     * @Param [username]
     * @return com.hmall.common.ServerResponse<com.hmall.model.SysUser>
     * @Description // 用以判断是否已经登录的User部分数据(拦截)
     */
    public ServerResponse<SysUser> simpleUserByUsername(String username) {
        SysUser user = userMapper.simpleUserByUsername(username);

        if (user != null) {
            return ServerResponse.createBySuccess(user);
        } else {
            return ServerResponse.createByError();
        }
    }


    public ServerResponse<Map<String, String>> getUser(Integer userId) {

        int status;
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByUserId(userId);
        if (sysUserTemp != null) {
            status = sysUserTempMapper.queryStatus(userId);
        } else {
            status = 0;
        }
        SysUserDept sysUserDept = sysUserDeptMapper.selectbyUserId(userId);
        if (sysUserDept != null){
            status = 3;
        }
        Map<String, String> map = new HashMap<>();
        map.put("status", String.valueOf(status));
        if (status == 3) {
            map.put("message", "资质通过");
        } else if (status == 0) {
            map.put("message", "未提交审核");
        } else if (status == 1) {
            map.put("message", "审核中");
        } else {
            map.put("message", "审核取消");
        }
        return ServerResponse.createBySuccess(map);

    }

    /**
     * @Date 2018/11/9 15:26
     * @Param [subName]
     * @return com.hmall.common.ServerResponse<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     * @Description // 公司模糊查询
     */
    public ServerResponse<List<Map<String, Object>>> queryCompany(String subName) {

        List<Map<String, Object>> deptName = sysDeptMapper.queryName(subName);
        if (deptName.size() == 0) {
            return ServerResponse.createByStatus(88, "找不到公司");
        }
        return ServerResponse.createBySuccess(deptName);
    }

    /**
     * @Date 2018/11/9 15:27
     * @Param [sysUserTempVo, userId]
     * @return com.hmall.common.ServerResponse
     * @Description // 完善用户信息
     */
    public ServerResponse prefectInformation(SysUserTempVo sysUserTempVo, Integer userId) {

        SysUserTemp sysUserTemp = new SysUserTemp();
        sysUserTemp.setUserId(userId);

        SysUserTemp oldUserTemp = sysUserTempMapper.selectByUserId(userId);
        //1. oldUserTemp == null
        //2. oldUserTemp != null 如果状态为 1 表示正在处理中不能提交资质 其他都可以
        //3. oldUserTemp != null 如果状态为 3  将temp表中的状态改为4 取消该资质
        // 删除detail表以及相关联的表
        if (oldUserTemp != null && oldUserTemp.getStatus() == 1) {
            return ServerResponse.createByStatus(16, "资质正在审核中，请勿重复提交");
        } else if (oldUserTemp != null && oldUserTemp.getStatus() == 3) {
            //更新上传过的记录 temp表
            oldUserTemp.setStatus(4);

            //如果原先审核已经通过 修改用户的权限为普通用户
            //sysUserRoleMapper.updateStatus(userId, 2);
            //修改
            int tempId = sysUserTempMapper.selectByUserId(userId).getTempId();
            sysUserTempMapper.updateStatus(tempId, 4);

            //删除detail表及其关联表保持资质唯一性
            //sysUserDetailMapper.
            sysUserDetailMapper.deleteByUserId(userId);
            sysUserDeptMapper.deleteByUserId(userId);
        }

        sysUserTemp.setAuthUrl(sysUserTempVo.getAuthUrl());
        sysUserTemp.setIdBackUrl(sysUserTempVo.getIdBackUrl());
        sysUserTemp.setIdFaceUrl(sysUserTempVo.getIdFaceUrl());
        sysUserTemp.setLicenseUrl(sysUserTempVo.getLicenseUrl());
        // sysUserTemp.setLinkmanName(sysUserTempVo.getLinkmanName());
        sysUserTemp.setLinkmanTel(sysUserTempVo.getLinkmanTel());
        sysUserTemp.setTaxCertUrl(sysUserTempVo.getTaxCertUrl());
        int type = "买家".equals(sysUserTempVo.getType()) ? 9 : 0;
        sysUserTemp.setType(type);
        //默认审核中
        sysUserTemp.setStatus(1);
        try {
            sysUserTempMapper.myInsert(sysUserTemp);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(16, "用户资料上传失败");
        }

        //2019/1/21 资质审核给后台发推送
        try {
            String username = userMapper.selectByPrimaryKey(userId).getUsername();
            jpushService.backPushMessage(userId, new Date(), 12, username);
        } catch (Exception e) {
            System.out.println("推送失败");
        }


        return ServerResponse.createBySuccess();
    }

    public ServerResponse<Integer> update(SysUser user) {

        return ServerResponse.createBySuccess(userMapper.updateByPrimaryKey(user));
    }

    /**
     * @Date 2018/11/9 15:28
     * @Param [userId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.SysDeptVo>
     * @Description // 查询买方名
     */
    ServerResponse<SysDeptVo> findBuyerDept(Integer userId) {
        //买方用户id查询部门id
        SysDeptVo deptVo;
        try {
            deptVo = sysUserDeptMapper.selectDeptByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.DEPT_SELECT_ISNULL_ERROR.getCode(), ResponseCode.DEPT_SELECT_ISNULL_ERROR.getDesc(), null);
        }
        if (null == deptVo) {
            return ServerResponse.createByStatus(ResponseCode.DEPT_SELECT_ISNULL_ERROR.getCode(), ResponseCode.DEPT_SELECT_ISNULL_ERROR.getDesc(), null);
        }
        return ServerResponse.createBySuccess(deptVo);
    }

    /**
     * @Date 2018/11/9 15:28
     * @Param [userId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.UnitContactVo>
     * @Description // 查询发票
     */
    public ServerResponse<UnitContactVo> selectInvoiceByUser(Integer userId) {
        UnitContactVo unitContactVo = new UnitContactVo();
        //
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        if (customerId == null) {
            return ServerResponse.createByErrorMessage("该用户暂未绑定公司");
        }
        Integer createUserId = sysCustomerMapper.selectCustomerUserId(customerId);
        if (createUserId == null) {
            return ServerResponse.createByErrorMessage("该公司暂未绑定业务员");
        }
        SysCustomer customer = sysCustomerMapper.selectByUserId(createUserId);
        unitContactVo.setInvoiceTitle(customer.getInvoiceTitle());
        unitContactVo.setTaxNum(customer.getTaxNum());
        unitContactVo.setBankName(customer.getBankName());
        unitContactVo.setBankAccount(customer.getBankNumber());

        return ServerResponse.createBySuccess(unitContactVo);

    }

    public ServerResponse<SysUserDetailVo> getPerfectInformation(Integer userId) {

        //1.通过userId查看user_dept表是否有了绑定
        //2.如果有关联的deptId 找dept_customer表
        //3.从customer表中取数据

        //sysUserDetailMapper

        //SysCustomerVo
        //资质信息,保证前端参数不变
        SysUserDetailVo userCustomerVo = sysCustomerMapper.selectByUserIdVo(userId);
        SysUser user = userMapper.selectByPrimaryKey(userId);
        if (userCustomerVo == null) {
            return ServerResponse.createByStatus(17, "还未通过资质审核，无法查看资质信息");
        }
        userCustomerVo.setLinkmanName(user.getRealName());
        userCustomerVo.setBusPersonName(user.getRealName());
        userCustomerVo.setLinkmanTel(user.getPhone());

        SysCustomer sysCustomer = sysCustomerMapper.selectByLikeCustomerName(userCustomerVo.getBusName());
        if(sysCustomer.getAuthUrl()==null){
            userCustomerVo.setAuthUrl("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1553071422080.png?Expires=1868431417&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=kPyrUyT3w25BgqLYpE0LHPsqXiE%3D");
        }else {
            userCustomerVo.setAuthUrl(sysCustomer.getAuthUrl());
        }
        if(sysCustomer.getLicenseUrl()==null){
            userCustomerVo.setLicenseUrl("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1553071422080.png?Expires=1868431417&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=kPyrUyT3w25BgqLYpE0LHPsqXiE%3D");
        }else {
            userCustomerVo.setLicenseUrl(sysCustomer.getLicenseUrl());
        }
        if(sysCustomer.getTaxCertUrl()==null){
            userCustomerVo.setTaxCertUrl("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1553071422080.png?Expires=1868431417&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=kPyrUyT3w25BgqLYpE0LHPsqXiE%3D");
        }else {
            userCustomerVo.setTaxCertUrl(sysCustomer.getTaxCertUrl());
        }
        if(sysCustomer.getIdFaceUrl()==null){
            userCustomerVo.setIdFaceUrl("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1553071422080.png?Expires=1868431417&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=kPyrUyT3w25BgqLYpE0LHPsqXiE%3D");
        }else {
            userCustomerVo.setIdFaceUrl(sysCustomer.getIdFaceUrl());
        }
        if(sysCustomer.getIdBackUrl()==null){
            userCustomerVo.setIdBackUrl("http://hd-yun.oss-cn-hangzhou.aliyuncs.com/imgupload/1553071422080.png?Expires=1868431417&OSSAccessKeyId=LTAI0AE4IXlOaSaX&Signature=kPyrUyT3w25BgqLYpE0LHPsqXiE%3D");
        }else {
            userCustomerVo.setIdBackUrl(sysCustomer.getIdBackUrl());
        }
        //名称不要变
        return ServerResponse.createBySuccess(userCustomerVo);
    }

    /**
     * @Date 2018/11/9 15:28
     * @Param [userId]
     * @return com.hmall.common.ServerResponse<com.hmall.model.SysUserTemp>
     * @Description // 获取审核信息
     */
    public ServerResponse<SysUserTemp> getTempPrefectInformation(Integer userId) {

        SysUserTemp userTemp = sysUserTempMapper.selectByUserId(userId);

        return ServerResponse.createBySuccess(userTemp);
    }


    public ServerResponse thirdLogin(String qqOpenId, String weChatOpenId, String agent, String deviceToken) throws IOException {

        SysUserExtra sysUserExtra = sysUserExtraMapper.selectByOpenId(qqOpenId, weChatOpenId);
        if (sysUserExtra == null) {
            //如果未绑定
            //1.未绑定手机  手机号未注册
            //头像和昵称进行覆盖

            //2.未绑定手机  手机已经注册过账号了
            //头像和昵称不进行覆盖
            return ServerResponse.createByStatus(111, "用户还未绑定手机");
        } else {
            //如果已经绑定了用户，后台进行登录
            SysUser user = userMapper.selectByPrimaryKey(sysUserExtra.getUserId());

            return loginSubMethod(user, agent, deviceToken);

        }

    }


    private String stoneRedis(String agent, SysUser user, JedisPool jedisPool){
        Jedis jedis = jedisPool.getResource();
        String agentUserName = agent + user.getUsername();

        String userToken = DataFomateUtil.sysUserToString(user);
        jedis.setex(agentUserName + "REDIS_USER", 24 * 1000 * 3600, userToken);

        // 检查是否已经登陆，如果已经登陆，就不用创建新Token并设置过期时间，如果是过期了，
        //为了测试设为30天  安卓和IOS需要登录永远有效
        //如果token在redis中没设置，设置到redis中

        //2018/10/26 新增需求
        //手机端（IOS+android)只能登陆一个账号
        //PC只能登录一个

        //手机端登录一次就吧全部都失效
        if("ANDROID-".equals(agent) || "IOS-".equals(agent)) {

            String androidKey = "ANDROID-" + user.getUsername();
            String iosKey = "IOS-" + user.getUsername();
            //挤出原来的所有token
            if (jedis.exists(androidKey)) {
                jedis.del(androidKey);
            }
            if (jedis.exists(iosKey)) {
                jedis.del(iosKey);
            }
        }

        String accessToken;
        accessToken = TokenUtil.createJwtToken(agentUserName);
        // Token超时间隔设为24小时
        if ("PC-".equals(agent)) {
            jedis.setex(agentUserName, 24  * 3600, accessToken);
        } else {
            jedis.setex(agentUserName, 24 * 3600 * 365 * 10, accessToken);
        }
        jedis.close();
        return accessToken;
    }

    public ServerResponse<LoginUserVo> loginSubMethod(SysUser user, String agent) throws IOException {

        return loginSubMethod(user, agent, null);
    }


    /**
     * @Date 2018/11/9 15:28
     * @Param [user, agent]
     * @return com.hmall.common.ServerResponse<java.util.Map<java.lang.String,java.lang.String>>
     * @Description // 账号密码验证结束之后，进行登录
     */
    public ServerResponse<LoginUserVo> loginSubMethod(SysUser user, String agent, String deviceToken) throws IOException {

        //手机端先给前者推送
        if(!"PC-".equals(agent) && !"XTXANDROID-".equals(agent) && !"XTXIOS-".equals(agent)) {
            String value = "1";
            //校验前者是不是就是这个deviceToken
            SysUserExtra userExtra = sysUserExtraMapper.selectByPrimaryKey(user.getUserId());
            if(userExtra != null){
                String oldDeviceToken = userExtra.getDeviceToken();
                if(deviceToken != null && oldDeviceToken != null){
                    if(!deviceToken.equals(oldDeviceToken)){
                        jpushController.jPushMethod("登出", "您的账号已在其他位置登录", user.getUsername(), "logout", value);
                    }
                }
            }
        }else{
            //PC端先给消息队列推送消息，然后删去这条消息队列

            Map<String, String> map = new HashMap<>();
            map.put("userName", user.getUsername());
            map.put("type", "logout");
            map.put("body", "登出推送");
            map.put("title", "登出推送标题");
            map.put("value", "1");
            map.put("isImport", "1");
            String url = envUtil.getPreUrl("order");

            HttpClientUtil.doGetWithParam(url + "/msg/directPcMsgPush", map);

            map.clear();
            map.put("exchange", "hmall_direct_exchg");
            map.put("routingKey", user.getUsername());
            HttpClientUtil.doGetWithParam(url + "/msg/deleteRoutingKey", map);
        }

        //更新deviceToken
        if(deviceToken != null) {
            sysUserExtraMapper.updateDeviceToken(user.getUserId(), deviceToken);
        }

        String accessToken = stoneRedis(agent, user, jedisPool);


        //如果token已经有了取出来
//
//        Map<String, String> tokenMap = new HashMap<>();
//        tokenMap.put("nickName", user.getQuestion());
//        tokenMap.put("avator", user.getAvatar());
//        tokenMap.put("token", accessToken);
//        tokenMap.put("userName", user.getUsername());
//        tokenMap.put("exchange", );
//        tokenMap.put("userId", user.getUserId().toString());
        int userId = user.getUserId();
        int status;
        SysUserTemp sysUserTemp = sysUserTempMapper.selectByUserId(userId);
        SysUserDept sysUserDept = sysUserDeptMapper.selectbyUserId(userId);
        if (sysUserDept!=null){
            status = 3;
        }else {
            if (sysUserTemp == null) {
                status = 0;
            } else {
                if(sysUserTemp.getStatus() == 3){
                    status = 0;
                }else{
                    status = sysUserTempMapper.queryStatus(userId);
                }


            }
        }

//        tokenMap.put("status", String.valueOf(status));


        //给出所有虚拟账号的token
        List<UserCustomerVo> userCustomerVoList = new ArrayList<>();

        List<SysUser> userList = userMapper.selectSubUser(user.getUsername());
        for(SysUser subUser: userList){
            if(!(subUser.getUsername().equals(user.getUsername().split("-")[0]) || subUser.getUsername().contains("-"))) {
                continue;
            }
            String subToken = stoneRedis(agent, subUser, jedisPool);
            if(subUser.getUserId() == userId){
                //然而已经变成subToken了
                accessToken = subToken;

            }
            SysCustomer customer = sysCustomerMapper.selectCustomerByUserId(subUser.getUserId());
            int subStatus;
            SysUserTemp subSysUserTemp = sysUserTempMapper.selectByUserId(subUser.getUserId());
            if (subSysUserTemp == null) {
                subStatus = 0;
            } else {
                subStatus = sysUserTempMapper.queryStatus(subUser.getUserId());
            }
            SysUserDept subSysUserDept = sysUserDeptMapper.selectbyUserId(subUser.getUserId());
            if (subSysUserDept!=null){
                subStatus = 3;
            }
            if(customer == null) {
                userCustomerVoList.add(new UserCustomerVo(null, null, subToken, subUser.getUserId(), subUser.getUsername(), subStatus, subUser.getAvatar(), subUser.getRealName()));

            }else {
                userCustomerVoList.add(new UserCustomerVo(customer.getCustomerId(), customer.getBusName(), subToken, subUser.getUserId(), subUser.getUsername(), subStatus, subUser.getAvatar(), subUser.getRealName()));
            }
        }

        LoginUserVo loginUserVo = new LoginUserVo(user.getQuestion(), user.getAvatar(), "front_message_exchg", user.getUsername(), user.getUserId(), accessToken, status, userCustomerVoList);

        SysCustomer customer = sysCustomerMapper.selectCustomerByUserId(user.getUserId());
        if(customer != null){
            loginUserVo.setCustomerId(customer.getCustomerId());
            loginUserVo.setCustomerName(customer.getBusName());
        }
//        tokenMap.put("userCustomer", userCustomerVoList.toString());

        //2018/12/6
        List<SysUser> subUserList = userMapper.selectSubUser(user.getUsername().split("-")[0]);
        List<Integer> salesmanIdList = new ArrayList<>();
        for(SysUser subUser : subUserList){
            if(!(subUser.getUsername().equals(user.getUsername().split("-")[0]) || subUser.getUsername().contains("-"))) {
                continue;
            }
            List<Integer> subSalsmanIdList = sysCustomerMapper.selectSalsmanByUserId(subUser.getUserId());
            salesmanIdList.addAll(subSalsmanIdList);
        }
        Set<Integer> set = new HashSet<>();
        set.addAll(salesmanIdList);
        salesmanIdList.clear();
        salesmanIdList.addAll(set);
//        set.clear();
//        Integer count = sysCustomerMapper.selectSalsmanCountByUserId(user.getUserId());
        //1表示是唯一业务员
        loginUserVo.setBackUniqueCheck(set.size() == 1 ? 1 : 0);
        set.clear();
        //登录成功后，如果没有alias插入，有的话更新

        if (agent.contains("PC")) {
            return ServerResponse.createBySuccess(loginUserVo);
        }
        //如果是PC端不操作
        Jedis jedis = jedisPool.getResource();
        for(SysUser subUser : userList) {
            int countUser = sysUserExtraMapper.selectByUserId(subUser.getUserId());

            String alias = agent.substring(0, agent.length() - 1) + "_" + subUser.getUsername();
            if (countUser == 0) {
                SysUserExtra sysUserExtra = new SysUserExtra();
                sysUserExtra.setUserId(subUser.getUserId());
                sysUserExtra.setAlias(alias);
                sysUserExtraMapper.insert(sysUserExtra);
            } else {
                sysUserExtraMapper.updateAlias(subUser.getUserId(), alias);
            }
            jedis.set("Alias-" + subUser.getUsername(), alias);
        }
        jedis.close();


        return ServerResponse.createBySuccess(loginUserVo);

    }

    /**
     * @Date 2018/11/9 15:29
     * @Param [qqOpenId, weChatOpenId, tel, nickName, avator, agent, core]
     * @return com.hmall.common.ServerResponse
     * @Description // 查询数据库中username为tel的是否存在
     */
    public ServerResponse telBinding(String qqOpenId, String weChatOpenId, String tel, String nickName, String avator, String agent, String core) {
        int count = userMapper.selectByUsername(tel);


        if (count <= 0) {
            //如果未查询到该手机的注册信息 进行注册 设置QQ或者微信的头像进去 然后帮助登录
            SysUser user = new SysUser();
            user.setUsername(tel);
            user.setQuestion(nickName);
            user.setAvatar(avator);
            user.setAnswer(core);

            //如果注册失败，返回注册失败的信息
            ServerResponse response = register(user);
            if (response.getStatus() != 0) {
                return response;
            }
            SysUser nowUser = userMapper.selectByUserName1(tel);
            //如果原来没有 进行插入操作
            int extraCount = sysUserExtraMapper.selectByUserId(nowUser.getUserId());
            if (extraCount <= 0) {
                SysUserExtra sysUserExtra = new SysUserExtra();
                sysUserExtra.setUserId(nowUser.getUserId());
                sysUserExtraMapper.insert(sysUserExtra);
            }

            SysUserExtra sysUserExtra = new SysUserExtra();
            //将QQ或者微信和用户绑定在一起
            int countUser = sysUserExtraMapper.selectByUserId(nowUser.getUserId());
            //更新和插入数据的区别
            if (countUser > 0) {
                //如果没绑定微信，绑定微信
                if (weChatOpenId != null) {
                    System.out.println("weChatOpenId" + weChatOpenId);
                    sysUserExtraMapper.updateWeChatOpenId(nowUser.getUserId(), weChatOpenId);
                }
                if (qqOpenId != null) {
                    //如果没绑定QQ，绑定QQ
                    System.out.println("qqOpenId" + qqOpenId);
                    sysUserExtraMapper.updateQOpenId(nowUser.getUserId(), qqOpenId);

                }
            } else {
                SysUserExtra sysUserExtra1 = new SysUserExtra();
                sysUserExtra.setUserId(nowUser.getUserId());
                sysUserExtra1.setQqOpenId(qqOpenId);
                sysUserExtra1.setWechatOpenId(weChatOpenId);
                sysUserExtraMapper.insert(sysUserExtra);
            }
            try {
                return loginSubMethod(nowUser, agent);
            } catch (IOException e) {
                return ServerResponse.createByErrorMessage("登陆失败");
            }
        } else {
            //如果查询到手机的注册信息  将QQ或者微信和用户绑定在一起
            // 1.有原信息并且原注册信息和现在信息一致 直接帮助登录
            // 2.没有原信息 帮助插入帮助登录
            // 3.原注册信息和现在信息不一致 提示该手机号已经被绑定过了
            SysUser nowUser = userMapper.selectByUserName1(tel);

            //如果原来没有 进行插入操作
            int extraCount = sysUserExtraMapper.selectByUserId(nowUser.getUserId());
            if (extraCount <= 0) {
                SysUserExtra sysUserExtra = new SysUserExtra();
                sysUserExtra.setUserId(nowUser.getUserId());
                sysUserExtraMapper.insert(sysUserExtra);
            }

            SysUserExtra userExtra = sysUserExtraMapper.selectExtraByUserId(nowUser.getUserId());


            if (weChatOpenId != null) {
                String oldWeChatId = userExtra.getWechatOpenId();
                if (oldWeChatId == null) {
                    sysUserExtraMapper.updateWeChatOpenId(nowUser.getUserId(), weChatOpenId);
                } else if (oldWeChatId.equals(weChatOpenId)) {

                } else {
                    return ServerResponse.createByStatus(112, "该手机号已经绑定了其他微信，无法再次绑定");
                }

            }

            if (qqOpenId != null) {
                String oldQQOpenId = userExtra.getQqOpenId();
                if (oldQQOpenId == null) {
                    //进行绑定
                    sysUserExtraMapper.updateQOpenId(nowUser.getUserId(), qqOpenId);
                } else if (!oldQQOpenId.equals(qqOpenId)) {
                    return ServerResponse.createByStatus(113, "该手机号已经绑定了其他QQ，无法再次绑定");
                }

            }

            try {
                return loginSubMethod(nowUser, agent);
            } catch (IOException e) {
                return  ServerResponse.createByErrorMessage("登陆失败");
            }
        }
    }

    /**
     * @Date 2018/11/9 15:31
     * @Param [userName, type]
     * @return com.hmall.common.ServerResponse
     * @Description // 都是未绑定手机号的
     */
    public ServerResponse bindCheckValid(String userName, String type) {

        String regex = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
        if (userName.length() != 11) {
            return ServerResponse.createByStatus(18, "请输入正确的手机号码");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(userName);
            boolean isMatch = m.matches();
            if (!isMatch) {
                return ServerResponse.createByStatus(18, "请输入正确的手机号码");
            }
        }

        int count1 = userMapper.selectByUsername(userName);
        if (count1 > 0) {
            //说明有用户 可以得到用户id
            int userId = userMapper.selectIdByUsername(userName);
            if ("QQ".equals(type)) {
                int count = sysUserExtraMapper.selectByUserId(userId);
                if (count > 0) {
                    SysUserExtra userExtra = sysUserExtraMapper.selectExtraByUserId(userId);
                    if (userExtra.getQqOpenId() != null) {
                        return ServerResponse.createByStatus(112, "该手机已经绑定了QQ了，请更换手机号");
                    }
                }
            } else if ("WeChat".equals(type)) {
                int count = sysUserExtraMapper.selectByUserId(userId);
                if (count > 0) {
                    SysUserExtra userExtra = sysUserExtraMapper.selectExtraByUserId(userId);
                    if (userExtra.getWechatOpenId() != null) {
                        return ServerResponse.createByStatus(113, "该手机号已经绑定了微信了，请更换手机号");
                    }
                }
            }
        }

        return ServerResponse.createBySuccessMessage("该手机号可以进行注册");
    }

    public ServerResponse huaWeiTokenRegister(String username, String deviceToken) {


        int userId = userMapper.selectIdByUsername(username);

        int count = sysUserExtraMapper.selectByUserId(userId);
        //判断extra表中是否有数据，没数据进行插入，否则一律进行更新
        if (count <= 0) {
            SysUserExtra sysUserExtra = new SysUserExtra();
            sysUserExtra.setUserId(userId);
            sysUserExtra.setDeviceToken(deviceToken);
            sysUserExtraMapper.insert(sysUserExtra);
        } else {
            sysUserExtraMapper.updateDeviceToken(userId, deviceToken);
        }

        return ServerResponse.createBySuccess();
    }



    /**
     * @Date 2018/11/9 15:31
     * @Param [rabbitKey]
     * @return com.hmall.common.ServerResponse<java.lang.String>
     * @Description // PC端访问传过来一个routing 返回二维码串
     */
    public ServerResponse<String> createQRcode(String rabbitKey) {

        Date date = new Date();
        long key = date.getTime();
        String strKey = key + "";
        String subKey = strKey.substring(0, 10);
        long uuid = RSA.rsa(Integer.valueOf(subKey), 57, 10L);
        Jedis jedis = jedisPool.getResource();
        String qRCode = "http://mall.hdnylon.com/login?uuid=" + String.valueOf(uuid);
        jedis.setex(qRCode, 120, rabbitKey);
        jedis.setex("QR" + qRCode, 5 * 60, rabbitKey);
        jedis.close();
        return ServerResponse.createBySuccess(qRCode);
    }


    /**
     * @Date 2018/11/9 15:31
     * @Param [QRCode, token]
     * @return com.hmall.common.ServerResponse
     * @Description //
     * 手机端识别好二维码后传过来二维码串
     *     1.推送消息到pc
     *     2.手机端回馈信息
     */
    public ServerResponse checkQRCode(String qRCode, String token) throws Exception {

        Jedis jedis = jedisPool.getResource();
        String rabbitKey = jedis.get(qRCode);
        Map<String, String> map = new HashMap<>();

        String nowRabbitKey = jedis.get("QR" + qRCode);
        map.put("key", nowRabbitKey);
        //如果是无效的消息
        String url = envUtil.getPreUrl("order");
        url += "/msg/pcMsgLoginDirectPush";

        if (rabbitKey == null) {

            ServerResponse response = ServerResponse.createByErrorMessage("二维码已失效，请刷新");
            String body = JSON.toJSONString(response);
            map.put("body", body);
            String s = HttpClientUtil.doGetWithParam(url, map);
            log.info(s);
            jedis.close();
            return ServerResponse.createByErrorMessage("二维码已失效，请刷新");
        } else {
            Claims claims = TokenUtil.parseJWT(token);
            String agentUserName = claims.getId();
            String[] str = AgentUtil.deleteAgentUserName(agentUserName).getData().split(":");
            String username = str[1];
            SysUser user = userMapper.selectByUserName1(username);
            String newToken = loginSubMethod(user, "PC-").getData().getToken();
            ServerResponse<String> response = ServerResponse.createBySuccess(newToken);
            String body = JSON.toJSONString(response);
            map.put("body", body);
            String s = HttpClientUtil.doGetWithParam(url, map);
            log.info(s);
            jedis.del("QR" + qRCode);
            jedis.del(qRCode);
            jedis.close();
            return ServerResponse.createBySuccess("扫码成功");
        }
    }

    public ServerResponse<UserExtraVo> getExtraInformation(Integer userId) {

        UserExtraVo userExtraVo = new UserExtraVo();

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
       // if(null == customerId) return ServerResponse.createByErrorMessage("该用户暂时未绑定公司");
        MallPaymentUnpay mallPaymentUnpay = null;
        SysCustomerCredit sysCustomerCredit = null;
       if(null != customerId) {
            mallPaymentUnpay = mallPaymentUnpayMapper.selectByPrimaryKey(customerId);

            sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
       }
        Double price;
        //如果是现金客户
        if(null == sysCustomerCredit){
            price = (null == mallPaymentUnpay) ? 0 : mallPaymentUnpay.getUnpayPayment().doubleValue();
        }else{
            //如果是账期客户
            //2018/10/11 不确定是否要减去账期
            price = Math.max(0.0, (null == mallPaymentUnpay ? 0 : mallPaymentUnpay.getUnpayPayment()).doubleValue());
        }

        //欠款额度
        userExtraVo.setArrears(price);

        //收藏
        userExtraVo.setCollection(0);

        //代金卷
        userExtraVo.setCoupon(0);

        //代金卷过期日期
        userExtraVo.setDate("12.30");

        //信誉
        userExtraVo.setReputation(5.0);

        //积分
        userExtraVo.setExchange(0);

        //vip等级
        userExtraVo.setVip(0);

        Integer simpleCount = orderMapper.selectSimpleOrderByUserId(userId);

        //拿样申请条数
        userExtraVo.setSampleCount(simpleCount);

        //待评价数
        Integer needCommentNum = 0;
        List<MallOrder> mallOrderList = orderMapper.selectByUserIdWithStatus(userId);
        for(MallOrder mallOrder : mallOrderList){
            List<MallOrderItem> mallOrderItemList = orderItemMapper.selectAllByOrderNo(mallOrder.getOrderNo());
            if(0 == mallOrderItemList.get(0).getCommentCheck()){
                needCommentNum++;
            }
        }

        int status = 0;
        SysUserDept sysUserDept = sysUserDeptMapper.selectbyUserId(userId);
        if(null != sysUserDept) {
            status = 1;
        }

        userExtraVo.setStatus(status);
        userExtraVo.setNeedComment(needCommentNum);
        return ServerResponse.createBySuccess(userExtraVo);
    }

    public ServerResponse<PCUserInformationVo>  getDetialInformation(Integer userId) {

        PCUserInformationVo pcUserInformationVo = new PCUserInformationVo();

        Integer customerType = 0;
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
        if(null != sysCustomerCredit) {
            customerType = 1;
        }
        pcUserInformationVo.setCustomerType(customerType);
        SysUser user = userMapper.selectByPrimaryKey(userId);
        pcUserInformationVo.setAvator(user.getAvatar());
        pcUserInformationVo.setNickName(user.getQuestion());
        pcUserInformationVo.setPhone(user.getUsername().split("-")[0]);
        pcUserInformationVo.setCredict(5.0);
        //待审核
        int checkStatus = 10;
        pcUserInformationVo.setNeedCheckNum(orderMapper.selectOrderCountByStatusAndUserId(userId, checkStatus));

        //待签合同
        int contractStatus = 35;
        pcUserInformationVo.setNeedContractNum(orderMapper.selectOrderCountByStatusAndUserId(userId, contractStatus));

        //待付款
        int paymentStatus = 30;
        pcUserInformationVo.setNeedPaymentNum(orderMapper.selectOrderCountByStatusAndUserId(userId, paymentStatus));

        //待发货
        int sendStatus = 20;
        pcUserInformationVo.setNeedSendNum(orderMapper.selectOrderCountByStatusAndUserId(userId, sendStatus));

        //待收货
        int collectionStatus = 40;
        pcUserInformationVo.setNeedCollectionNum(orderMapper.selectOrderCountByStatusAndUserId(userId, collectionStatus));

        //待评价
        //发货一次就能进行评价
        int commentStatus = 60;
        List<Long> orderNoList = orderMapper.selectOrderNoListByUserIdAndStatus(userId, commentStatus);
        int count = 0;
        for (Long a : orderNoList) {
            count += (1 - orderItemMapper.selectCommentCheck(a));
        }
        pcUserInformationVo.setNeedCommentNum(count);

        //待换货
        pcUserInformationVo.setNeedExchangeNum(0);

        pcUserInformationVo.setRestMoney(0.0);

        pcUserInformationVo.setWhiteBar(0.0);
        pcUserInformationVo.setSecurity(0.60);
        String tips ;

        Date date = new Date();
        //没必要这么长
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        System.out.println(dateStr);
        String []subDateStr = dateStr.split(" ");

        Integer hour = Integer.valueOf(subDateStr[1].split(":")[0]);

        if (hour >= 6 && hour < 12) {
            tips = "元气满满的一天从华鼎开始!";
        } else if (hour >= 12 && hour < 18) {
            tips = "加油，华鼎与您共度午后时光!";
        } else {
            tips = "工作了一天，记得休息哦~";
        }

        pcUserInformationVo.setTips(tips);

        pcUserInformationVo.setVip("0");

        //用户主键
        pcUserInformationVo.setUserId(userId);

        //设置子账号信息
        List<UserCustomerVo> userCustomerVoList = new ArrayList<>();
        List<SysUser> userList = userMapper.selectSubUser(user.getUsername().split("-")[0]);

        Jedis jedis = jedisPool.getResource();
        int subStatus;
        for(SysUser subUser : userList){
            if(!(subUser.getUsername().equals(user.getUsername().split("-")[0]) || subUser.getUsername().contains("-"))) {
                continue;
            }


            SysCustomer customer = sysCustomerMapper.selectByUserId(subUser.getUserId());
            String token;
            if(!jedis.exists("PC-" + subUser.getUsername())){
                token = null;
            }else{
                token = jedis.get("PC-" + subUser.getUsername());
            }
            SysUserTemp sysUserTemp = sysUserTempMapper.selectByUserId(subUser.getUserId());
            if(sysUserTemp == null){
                subStatus = 0;
            }else{
                subStatus = sysUserTemp.getStatus();
            }
            SysUserDept sysUserDept = sysUserDeptMapper.selectbyUserId(subUser.getUserId());
            if (sysUserDept!=null){
                subStatus=3;
            }

            if(customer == null){
                userCustomerVoList.add(new UserCustomerVo(null, null, token, subUser.getUserId(), subUser.getUsername(), subStatus, subUser.getAvatar(), subUser.getRealName()));
            }else{
                userCustomerVoList.add(new UserCustomerVo(customer.getCustomerId(), customer.getBusName(), token, subUser.getUserId(), subUser.getUsername(), subStatus, subUser.getAvatar(), subUser.getRealName()));
            }
        }

        pcUserInformationVo.setUserCustomerVo(userCustomerVoList);
        return ServerResponse.createBySuccess(pcUserInformationVo);

    }

    /**
     * @Date 2018/11/9 15:35
     * @Param [userId, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo<com.hmall.vo.SampleVo>>
     * @Description // 列出该用户的所有拿样的信息
     */
    public ServerResponse<PageVo<SampleVo>> getDetailInformationSample(Integer userId, Integer pageNum, Integer pageSize) {

        List<SampleVo> sampleVoList = new ArrayList<>();
        int realPageNum = (pageNum - 1) * pageSize;
        int total = 0;
        //orderNoList
        List<BigInteger> orderNoList = orderMapper.selectSampleNoByUserId(userId);

        if (orderNoList.size() != 0) {
            List<MallOrderItem> mallOrderItemList = orderItemMapper.selectByOrderNoList(orderNoList);

            total = mallOrderItemList.size();

            for (int i = 0; i < pageSize; i++) {
                if ((realPageNum + i) >= total) {
                    continue;
                }
                MallOrderItem mallOrderItem = mallOrderItemList.get(realPageNum + i);
                SampleVo sampleVo = new SampleVo();
                sampleVo.setGrade(mallOrderItem.getGrade());

                MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(mallOrderItem.getProductId());
                //属性
                if(mallProduct == null) {
                    total--;
                    continue;
                }
                String name = mallProduct.getName();
                String []subName = name.split(",", -1);
                String realName = subName[1] + " " + subName[6] + " " + subName[7] + " " + subName[3] + "D" + subName[4] + "F" + " " + subName[8] + " " + subName[9];
                sampleVo.setName(realName);

                sampleVo.setModel(subName[2]);
                //日期

                sampleVo.setDateTime(mallOrderItem.getUpdateTime());

                sampleVo.setImg(mallProduct.getMainImage().split(",")[0]);
                sampleVo.setType(subName[0]);
                sampleVo.setWeight(mallOrderItem.getQuantity() + "kg");

                String shopName = mallShopMapper.selectShopNameByOrderId(mallProduct.getShopId());
                sampleVo.setShopName(shopName);
                sampleVoList.add(sampleVo);
            }
        }

        PageVo<SampleVo> pageVo = new PageVo<>(realPageNum, pageSize, total, sampleVoList);
        return ServerResponse.createBySuccess(pageVo);

    }


    /**
     * @Date 2018/11/8 16:48
     * @Param []
     * @return com.hmall.common.ServerResponse<com.hmall.vo.ProductCommend>
     * @Description //
     * 每日推荐机制
     *     1.优先新品
     *     2.优先销量高 因为销量是定时任务每天更新一次就相当于是每日更改一次（产品新品不改变）
     *     3.等级选最高的（不能随机）
     */
    public ServerResponse<ProductCommend> getDetailInformationRecommend() {

        ProductCommend productCommend = new ProductCommend();

        //所有新品的集合
        List<Integer> newProductIdList = mallProductMapper.selectAllNewProductId();

        //从所有新品中选出销量最高的产品
        Integer productId = -1;
        if(newProductIdList.size() != 0){
            productId = mallHotMapper.selectOneByList(newProductIdList);
        }
        if(productId == -1){
            productId = mallProductMapper.selectMin();
        }
        MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(productId);
        productCommend.setProductId(productId);

        String grade = mallPriceMapper.selectMaxGradeByProductId(productId);
        productCommend.setGrade(grade);
        productCommend.setImg(mallProduct.getMainImage().split(",")[0]);
        String shopName = mallShopMapper.selectByPrimaryKey(mallProduct.getShopId()).getShopName();
        productCommend.setShopName(shopName);


        //属性
        String name = mallProduct.getName();
        String []subName = name.split(",", -1);
        String realName = subName[1] + " " + subName[6] + " " + subName[7] + " " + subName[3] + "D" + subName[4] + "F" + " " + subName[8] + " " + subName[9];
        productCommend.setName(realName);
        productCommend.setType(subName[0]);
        productCommend.setModel(subName[2]);
        return ServerResponse.createBySuccess(productCommend);
    }


    /**
     * @Date 2018/11/9 15:36
     * @Param [userId, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo<com.hmall.vo.ProductVip>>
     * @Description // 会员推荐
     */
    public ServerResponse<PageVo<ProductVip>> getDetailInformationVip(Integer pageNum, Integer pageSize) {

        int readPageNum = (pageNum - 1) * pageSize;
        int total = mallProductMapper.selectTotal();
        List<MallProduct> mallProductList = mallProductMapper.selectSomeProduct(readPageNum, pageSize);

        List<ProductVip> productVipList = new ArrayList<>();

        for (MallProduct mallProduct : mallProductList) {
            int productId = mallProduct.getId();
            ProductVip vip = new ProductVip();

            String grade = mallPriceMapper.selectMaxGradeByProductId(productId);
            vip.setGrade(grade);
            vip.setImg(mallProduct.getMainImage().split(",")[0]);

            //属性
            String name = mallProduct.getName();
            String []subName = name.split(",", -1);
            String realName = subName[1] + " " + subName[6] + " " + subName[7] + " " + subName[3] + "D" + subName[4] + "F" + " " + subName[8] + " " + subName[9];
            vip.setName(realName);
            vip.setType(subName[0]);
            vip.setModel(subName[2]);
            vip.setProductId(productId);
            String shopName = mallShopMapper.selectByPrimaryKey(mallProduct.getShopId()).getShopName();
            vip.setShopName(shopName);
            productVipList.add(vip);
        }

        PageVo<ProductVip> pageVo = new PageVo<>(readPageNum, pageSize, total, productVipList);
        return ServerResponse.createBySuccess(pageVo);
    }


    public ServerResponse<Integer> getInformationFavorite(Integer userId) {

        int count = sysUserFavoriteMapper.selectCountByUserId(userId);
        return ServerResponse.createBySuccess(count);
    }


    /**
     * @Date 2018/11/9 15:37
     * @Param [userId, oldPassword, newPassword]
     * @return com.hmall.common.ServerResponse
     * @Description //
     * 一共两次加密
     *     普通用户 前端一次md5后台一次md5
     *     办事处人 前端一次md5后台一次security
     */
    public ServerResponse changePassword(Integer userId, String oldPassword, String newPassword) {
        Jedis jedis = jedisPool.getResource();
        //..不规范
        SysUser user = userMapper.selectByPrimaryKey(userId);
        //如果是办事处的
        if (user.getDeptId() != null) {
            if (ENCODER.matches(oldPassword, user.getPassword())) {
                //1.如果匹配了可以修改
                String nowPassword = ENCODER.encode(newPassword);
                user.setPassword(nowPassword);
                user.setUpdateTime(new Date());
                userMapper.updateByPrimaryKey(user);

                //2.要清空redis中保存的键值对，因为后台登录要判断
                jedis.del(user.getUsername());
            } else {
                jedis.close();
                return ServerResponse.createByErrorMessage("尊敬的业务员，您的密码有误，请重新输入");
            }
        } else {
            //如果是普通用户修改密码

            if (MD5Util.MD5EncodeUtf8(oldPassword).equals(user.getPassword())) {
                //1.匹配了可以修改
                String nowPassword = MD5Util.MD5EncodeUtf8(newPassword);
                user.setPassword(nowPassword);
                user.setUpdateTime(new Date());
                userMapper.updateByPrimaryKey(user);

                //删除可能所有存在的键值
                //一个思路，可以不删，因为该后台是覆盖操作
                //1.WECHAT-  2.IOS- 3.PC- 4.ANDROID
                JedisUtils.delKeyValue(jedis, user.getUsername());
            } else {
                jedis.close();
                return ServerResponse.createByErrorMessage("尊敬的用户，您的密码有误，请重新输入");
            }
        }
        jedis.close();
        return ServerResponse.createBySuccess("密码修改成功");
    }

    public ServerResponse<StatementOfAccountVo> getStatementOfAccountUp(Integer customerId, Integer year, Integer month) {

        StatementOfAccountVo statementOfAccountVo = new StatementOfAccountVo();
        SysCustomerStatement sysCustomerStatement = sysCustomerStatementMapper.selectAccount(customerId, year, month + 1);
        statementOfAccountVo.setLastMonthUnpayment(null == sysCustomerStatement ? new BigDecimal(0) : sysCustomerStatement.getLastMonthUnpayment());
        statementOfAccountVo.setThisMonthFufillmentPayment(null == sysCustomerStatement ? new BigDecimal(0) : sysCustomerStatement.getThisMonthFufillmentPayment());
        statementOfAccountVo.setThisMonthReturnPayment(null == sysCustomerStatement ? new BigDecimal(0) : sysCustomerStatement.getThisMonthReturnPayment());
        statementOfAccountVo.setThisMonthUnpayment(null == sysCustomerStatement ? new BigDecimal(0) : sysCustomerStatement.getThisMonthUnpayment());

        //去voucher表里面看时间在当前月份的凭据
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startTime = calendar.getTime();

        calendar.set(Calendar.MONTH, month + 1);
        Date endTime = calendar.getTime();

        List<Integer> customerUserIdList = sysUserDeptMapper.selectUserIdListByCustomerId(customerId);

        List<MallPaymentVoucher> mallPaymentVoucherList = new ArrayList<>();
        if(0 != mallPaymentVoucherList.size()) {
            mallPaymentVoucherList = mallPaymentVoucherMapper.selectByCustomerUserIdList(startTime, endTime, customerUserIdList);
        }

        List<PaymentVoucherVo> paymentVoucherVoList = new ArrayList<>();
        for (MallPaymentVoucher mallPaymentVoucher : mallPaymentVoucherList) {
            PaymentVoucherVo paymentVoucherVo = new PaymentVoucherVo();
            paymentVoucherVo.setPayment(mallPaymentVoucher.getFactPayment());
            paymentVoucherVo.setPaymentImg(mallPaymentVoucher.getVoucherImg());
            paymentVoucherVo.setPaymentTime(mallPaymentVoucher.getCreateTime());
            paymentVoucherVo.setStatus(mallPaymentVoucher.getIsAdopt());
            //如果这个交易凭证有订单号说明是现金的
            if (null != mallPaymentVoucher.getOrderNo()) {
                paymentVoucherVo.setPaymentType(0);
            }
            //1表示账期的
            else {
                paymentVoucherVo.setPaymentType(1);
            }
            paymentVoucherVoList.add(paymentVoucherVo);
        }

        statementOfAccountVo.setPaymentVoucherCount(paymentVoucherVoList.size());
        return ServerResponse.createBySuccess(statementOfAccountVo);
    }

    public ServerResponse<PageVo<PaymentVoucherVo>> getStatementOfAccountDown(List<Integer> customerIdList, Integer year, Integer month, Integer pageNum, Integer pageSize) {

        //去voucher表里面看时间在当前月份的凭据
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startTime = calendar.getTime();

        calendar.set(Calendar.MONTH, month + 1);
        Date endTime = calendar.getTime();

        List<Integer> customerUserIdList = new ArrayList<>();
        for(Integer customerId : customerIdList) {
            customerUserIdList.addAll(sysUserDeptMapper.selectUserIdListByCustomerId(customerId));
        }

        List<MallPaymentVoucher> mallPaymentVoucherList = mallPaymentVoucherMapper.selectByCustomerUserIdList(startTime, endTime, customerUserIdList);

        List<PaymentVoucherVo> paymentVoucherVoList = new ArrayList<>();
        for (MallPaymentVoucher mallPaymentVoucher : mallPaymentVoucherList) {
            PaymentVoucherVo paymentVoucherVo = new PaymentVoucherVo();
            paymentVoucherVo.setPaymentVoucherId(mallPaymentVoucher.getVoucherId());
            paymentVoucherVo.setPayment(mallPaymentVoucher.getFactPayment());
            paymentVoucherVo.setPaymentImg(mallPaymentVoucher.getVoucherImg());
            paymentVoucherVo.setPaymentTime(mallPaymentVoucher.getCreateTime());
            paymentVoucherVo.setStatus(mallPaymentVoucher.getIsAdopt());
            paymentVoucherVo.setOrderNo(mallPaymentVoucher.getOrderNo());
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(mallPaymentVoucher.getUserId());
            paymentVoucherVo.setCustomerId(customerId);
            paymentVoucherVo.setCustomerName(sysCustomerMapper.selectByPrimaryKey(customerId).getBusName());


            //如果这个交易凭证有订单号说明是现金的
            if (null != mallPaymentVoucher.getOrderNo()) {
                paymentVoucherVo.setPaymentType(0);
            }
            //1表示账期的
            else {
                paymentVoucherVo.setPaymentType(1);
            }
            paymentVoucherVoList.add(paymentVoucherVo);
        }

        Integer start = pageSize * (pageNum - 1);
        Integer end = Math.min(paymentVoucherVoList.size(), start + pageSize);
        List<PaymentVoucherVo> subPaymentVoucherVo = paymentVoucherVoList.subList(start, end);
        PageVo<PaymentVoucherVo> pageVo = new PageVo<>(pageNum, pageSize, paymentVoucherVoList.size(), subPaymentVoucherVo);
        return ServerResponse.createBySuccess(pageVo);
    }

    public ServerResponse<List<AccountHistoryVo>>  getStatementOfAccountHistory(List<Integer> customerIdList, int tYear) {

//        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        //12个月
        //判断是否显示的条件
        //1.当前月份是否有发货记录
        //2.前月份是否有回款记录


        List<AccountHistoryVo> accountHistoryVoList = new ArrayList<>();

        //前置当前月
        Calendar calendar = Calendar.getInstance();
        int thisMonth = calendar.get(Calendar.MONTH) + 1;
        for(Integer customerId : customerIdList) {
            SysCustomerStatement sysCustomerStatement = sysCustomerStatementMapper.selectAccount(customerId, tYear, thisMonth);
            if (null != sysCustomerStatement && null != sysCustomerStatement.getThisMonthUnpayment() && null != sysCustomerStatement.getThisMonthReturnPayment()) {
                AccountHistoryVo accountHistoryVo = new AccountHistoryVo();
                accountHistoryVo.setYear(tYear);
                accountHistoryVo.setMonth(thisMonth);
                accountHistoryVo.setThisMonthReturnPayment(null == sysCustomerStatement.getThisMonthReturnPayment() ? new BigDecimal(0) : sysCustomerStatement.getThisMonthReturnPayment());
                accountHistoryVo.setThisMonthUnpayment(null == sysCustomerStatement.getThisMonthFufillmentPayment() ? new BigDecimal(0) : sysCustomerStatement.getThisMonthFufillmentPayment());
                accountHistoryVo.setCustomerId(customerId);
                accountHistoryVo.setImg(sysCustomerStatement.getImage());
                int customerType = 0;
                SysCustomerCredit sysCustomerCredit = sysCustomerCreditMapper.selectByCustomerId(customerId);
                if(null != sysCustomerCredit) {
                    customerType = 1;
                }
                accountHistoryVo.setCustomerType(customerType);

                accountHistoryVo.setCustomerName(sysCustomerMapper.selectByPrimaryKey(customerId).getBusName());
                accountHistoryVoList.add(accountHistoryVo);
            }
        }

        for (int i = 1; i <= 12; i++) {
            if (i == thisMonth) {
                continue;
            }
            for (Integer customerId : customerIdList) {
                SysCustomerStatement sysCustomerStatement = sysCustomerStatementMapper.selectAccount(customerId, tYear, i);
                if (null == sysCustomerStatement) {
                    continue;
                }
                if (null == sysCustomerStatement.getThisMonthUnpayment() || null == sysCustomerStatement.getThisMonthReturnPayment()) {
                    continue;
                }

                AccountHistoryVo accountHistoryVo = new AccountHistoryVo();
                accountHistoryVo.setYear(tYear);
                accountHistoryVo.setMonth(i);
                accountHistoryVo.setThisMonthReturnPayment(null == sysCustomerStatement.getThisMonthReturnPayment() ? new BigDecimal(0) : sysCustomerStatement.getThisMonthReturnPayment());
                accountHistoryVo.setThisMonthUnpayment(null == sysCustomerStatement.getThisMonthUnpayment() ? new BigDecimal(0) : sysCustomerStatement.getThisMonthUnpayment());
                accountHistoryVo.setCustomerId(customerId);
                accountHistoryVo.setCustomerName(sysCustomerMapper.selectByPrimaryKey(customerId).getBusName());
                accountHistoryVoList.add(accountHistoryVo);
            }
        }
        return ServerResponse.createBySuccess(accountHistoryVoList);
    }


    public ServerResponse<InvoiceVo> getInvoiceInformation(Integer userId) {

//        Integer createUserId = findCreateUserIdByUserId(userId);
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        if(null == customerId) {
            return ServerResponse.createByErrorMessage("该用户暂未绑定公司");
        }
        SysCustomer customer = sysCustomerMapper.selectByPrimaryKey(customerId);
        InvoiceVo invoiceVo = new InvoiceVo(customer.getInvoiceTitle(), customer.getTaxNum(), customer.getBankName(), customer.getBankNumber(), customer.getInvoiceReceivemanName(), customer.getInvoiceReceivemanTel(), customer.getInvoiceReceivemanAddress());
        return ServerResponse.createBySuccess(invoiceVo);
    }

    public ServerResponse updateInvoiceInformation(Integer userId, String invoiceReceivemanName, String invoiceReceivemanTel, String invoiceReceivemanAddress) {

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        if(null == customerId) {
            return ServerResponse.createByErrorMessage("该用户未绑定公司");
        }

        try {
            sysCustomerMapper.updateReceivemanInformation(customerId, invoiceReceivemanName, invoiceReceivemanTel, invoiceReceivemanAddress);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("更新失败");
        }

        return ServerResponse.createBySuccess();
    }


    public ServerResponse<List<AccountOrderVo>> getStatementOfAccountOrderDetail(List<Integer> customerIdList, Integer year, Integer month) {

        List<AccountOrderVo> accountOrderVoList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date start = calendar.getTime();
        if (month == 12) {
            month = 1;
            calendar.set(Calendar.YEAR, year + 1);
        }
        calendar.set(Calendar.MONTH, month + 1);
        Date end = calendar.getTime();

        List<Long> orderNoList = new ArrayList<>();
        for(Integer customerId : customerIdList) {
//            orderNoList.addAll(mallOrderFufillmentParentMapper.selectOrderNoByArgs(start, end, customerId));
            //2019/1/14 状态从发货中转移到待发货
            orderNoList.addAll(orderMapper.selectByCustomerIdWithTime(start, end, customerId));
        }
        for (Long orderNo : orderNoList) {
            AccountOrderVo accountOrderVo = new AccountOrderVo();
            accountOrderVo.setOrderNo(orderNo);
            MallOrder mallOrder = orderMapper.selectAllByOrderNo(orderNo);
            if(null != mallOrder) {
                accountOrderVo.setOrderTime(orderMapper.selectByOrderNo(orderNo).getCreateTime());
            }else{
                continue;
            }
            accountOrderVoList.add(accountOrderVo);
        }

        return ServerResponse.createBySuccess(accountOrderVoList);
    }

    /**
     * @Date 2018/11/9 15:38
     * @Param []
     * @return com.hmall.common.ServerResponse
     * @Description //  更新用户类型
     */
    public ServerResponse updateCustomerType() {

        Calendar calendar = Calendar.getInstance();
        Date start = calendar.getTime();
        List<SysCustomerCreditTransaction> sysCustomerCreditTransactionList = sysCustomerCreditTransactionMapper.selectNoEffective(start);

        for(SysCustomerCreditTransaction sysCustomerCreditTransaction : sysCustomerCreditTransactionList){

            //先更新历史表
            sysCustomerCreditTransactionMapper.updateStatus(sysCustomerCreditTransaction.getSysCustomerCreditTransactionId(), 1);

            //再更新客户表
            sysCustomerCreditMapper.updateCustomer(sysCustomerCreditTransaction.getAccountPeriod(), sysCustomerCreditTransaction.getQuota(), sysCustomerCreditTransaction.getCustomerId());
        }
        return ServerResponse.createBySuccess();
    }

    public List<Integer> getCustomerUserIdByArgs(Integer userId, Integer customerId, Integer type) {


        List<Integer> customerIdList = new ArrayList<>();
        //如果是前端的调用，只需要传递token
        if(type == 1){
            //前端不传递customerId
            customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
            customerIdList.add(customerId);
        }else{
            //如果是后端的调用
            //一.人员的权限
            //1.对于管理员 得到管理员下的所有的公司
            //2.对于业务员 得到业务员管理的公司

            //
            List<String> menuList = menuMapper.listMenuByUserId(userId);
            int role = DealerMenuUtil.getBackRole(menuList);

            //根据不同的权限得到不同的客户列表
            if (role == 0) {
                //业务员只能看到自己绑定的公司的信息
                customerIdList =  sysCustomerMapper.selectCustomerIdLisstBySalsemanId(userId);
            } else {
                //管理员可以看到下面所有的业务员的绑定的公司的信息
                List<Integer> salesmanIdList = userMapper.selectUserIdListByDeptId((userMapper.selectByPrimaryKey(userId).getDeptId()));
                for (Integer salesmanId : salesmanIdList) {
                    customerIdList.addAll(sysCustomerMapper.selectCustomerIdLisstBySalsemanId(salesmanId));
                }
            }


            //二.筛选
            //1.如果不传递customerId 默认所有的公司
            //2.如果指定了customerId

            List<Integer> newCustomerIdList = new ArrayList<>();
            if(null != customerId && !"".equals(customerId)){
                for(int i = 0; i < customerIdList.size(); i++){
                    if(customerId.equals(customerIdList.get(i))){
                        newCustomerIdList.add(customerId);
                    }
                }

                customerIdList.clear();
                customerIdList.addAll(newCustomerIdList);
            }
        }

        return customerIdList;
    }

    public ServerResponse checkLogin(String agentUserName) {

        //带了设备头  ANDROID- , IOS- , PC-
        String []str = AgentUtil.deleteAgentUserName(agentUserName).getData().split(":");
        String agent = str[0];
        String username = str[1];

        Jedis jedis = jedisPool.getResource();

        if("PC-".equals(agent)){
            if(jedis.exists(agentUserName)){
                return ServerResponse.createByErrorMessage("PC端已经有账号登录，请确认是否强制登陆");
            }
        }else{
            if(jedis.exists("IOS" + username)){
                return ServerResponse.createByErrorMessage("IOS端已经有账号登陆，请确认是否强制登陆");
            }else{
                return ServerResponse.createByErrorMessage("Android已经有账号登陆，请确认是否强制登陆");
            }
        }

        return ServerResponse.createBySuccess("可以进行登录操作");

    }

    /**
     * @Date 2018/11/8 16:36
     * @Param [url, accessToken, openId]
     * @return com.hmall.common.ServerResponse
     * @Description //qq 登录
     */
    public ServerResponse qqLogin(String url) {


        ServerResponse response = getJson(url);
        if(response.getStatus() != 0) {
            return response;
        }
        JSONObject json = (JSONObject)response.getData();
        Map<String, String> userMap = new HashMap<>();
        userMap.put("nickName", json.getString("nickname"));
        userMap.put("avator", json.getString("figureurl_qq_2"));
        return ServerResponse.createBySuccess(userMap);
    }

    private ServerResponse<JSONObject> getJson(String url){
        Document document;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            return ServerResponse.createByErrorMessage("登录失败");
        }
        String resultText = document.text();
        JSONObject json = JSON.parseObject(resultText);
        return ServerResponse.createBySuccess(json);
    }

    public ServerResponse weChatLogin(String url) {

        ServerResponse response = getJson(url);
        if(response.getStatus() != 0) {
            return response;
        }
        JSONObject json = (JSONObject) response.getData();

        if(json.getString("errcode") != null){
            return ServerResponse.createByError();
        }

        String accessToken = json.getString("access_token");
        String openId = json.getString("openid");
        String refreshToken = json.getString("refresh_token");
//        校验token是否失效
//        url = "https://api.weixin.qq.com/sns/auth?access_token=" + ACCESS_TOKEN&openid=OPENID";

        //请求用户信息
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
        response = getJson(url);
        if(response.getStatus() != 0){
            return response;
        }
        json = (JSONObject)response.getData();

        if(json.getString("errcode") != null){
            return ServerResponse.createByError();
        }


        openId = json.getString("openid");
        String nickname = json.getString("nickname");
        String avator = json.getString("headimgurl");
        Map map = new HashMap();
        map.put("accessToken", accessToken);
        map.put("openId", openId);
        map.put("nickName", nickname);
        map.put("avator", avator);

        SysUserExtra userExtra = sysUserExtraMapper.selectByOpenId(null, openId);
        if(userExtra != null){
            map.put("userId", userExtra.getUserId());
        }else{
            map.put("userId", "");
        }

        return ServerResponse.createBySuccess(map);

    }

    public ServerResponse<String> logout(JedisPool jedisPool, String token) {

        Jedis jedis = jedisPool.getResource();
        Claims claims = TokenUtil.parseJWT(token);
        String agentUserName = claims.getId();

        String []str = AgentUtil.deleteAgentUserName(agentUserName).getData().split(":");
        String agent = str[0];
        String username = str[1];

        //要等出所有账号
        List<SysUser> userList = userMapper.selectSubUser(username.split("-")[0]);
        for(SysUser subUser : userList) {
            if(!(subUser.getUsername().equals(username.split("-")[0]) || subUser.getUsername().contains("-"))) {
                continue;
            }
            jedis.del(agent + subUser.getUsername());
            String key = agent + subUser.getUsername()+ "REDIS_USER";
            jedis.del(key);
        }
        jedis.close();
        return ServerResponse.createBySuccess("登出成功");
    }



}
